
package com.killcalorie.wjduan.message


import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.net.URI

// https://docs.namichong.com/kotlin/jvm-spring-boot-using-crudrepository.html#update-your-application





@RestController
@RequestMapping("/api/message")
class MessageController(private val service: MessageService) {
    @GetMapping
    fun listMessages() = ResponseEntity.ok(service.findMessages())


    //curl -X POST --location "http://localhost:8080/api/message/putmessage" -H "Content-Type: application/json" -d "{ \"id\":1,\"text\": \"Hello\" }"
    //curl -X POST --location "http://localhost:8080/api/getmessage" -H "Content-Type: application/json" -d "{ \"text\": \"Hello\" }"
    //curl -X GET  --location "http://localhost:8080"

    @PostMapping("/putmessage")
    fun post(@RequestBody message: Message): ResponseEntity<Message> {
        val savedMessage = service.save(message)
        return ResponseEntity.ok().body(savedMessage)
        // return ResponseEntity.created(URI("/${savedMessage.id}")).body(savedMessage)
    }

    @GetMapping("/getmessage/{id}")
    fun getMessage(@PathVariable id: String): ResponseEntity<Message> =
        service.findMessageById(id).toResponseEntity()

    private fun Message?.toResponseEntity(): ResponseEntity<Message> =
        // 如果消息为空（未找到），则将响应代码设置为 404
        this?.let { ResponseEntity.ok(it) } ?: ResponseEntity.notFound().build()
}